from django import template

register = template.Library()

@register.filter
def multiply(value, arg):
    """乘法过滤器"""
    try:
        return float(value) * float(arg)
    except (ValueError, TypeError):
        return 0


@register.filter
def get_mastery_level(mastery_level):
    """根据掌握度返回等级名称"""
    if mastery_level >= 0.8:
        return 'excellent'
    elif mastery_level >= 0.6:
        return 'good'
    elif mastery_level >= 0.4:
        return 'average'
    else:
        return 'poor'

@register.filter
def get_subject_id(subject_name):
    """根据科目名称获取科目ID"""
    try:
        from score.models import Subject
        subject = Subject.objects.get(name=subject_name)
        return subject.id
    except Subject.DoesNotExist:
        return 0

@register.filter
def get_subject_color(subject_name):
    """根据科目名称获取科目颜色"""
    try:
        from score.models import Subject
        subject = Subject.objects.get(name=subject_name)
        return subject.color or '#6c757d'
    except Subject.DoesNotExist:
        return '#6c757d'

@register.filter
def divide(value, arg):
    """除法过滤器"""
    try:
        return float(value) / float(arg)
    except (ValueError, TypeError, ZeroDivisionError):
        return 0


@register.filter
def index(indexable, i):
    """获取列表索引的过滤器"""
    try:
        return indexable[i]
    except (IndexError, TypeError):
        return None


@register.filter
def get_by_id(queryset, id):
    """根据ID从查询集中获取对象"""
    try:
        return queryset.get(id=id)
    except:
        return None

@register.filter
def get_result_display(value):
    """获取练习结果的显示名称"""
    from analysis.models import KnowledgePracticeRecord
    for result_value, result_name in KnowledgePracticeRecord.PRACTICE_RESULT_CHOICES:
        if str(result_value) == str(value):
            return result_name
    return value

@register.filter
def get_status_color(status_name):
    """根据学习状态名称获取颜色"""
    color_map = {
        '未开始': '#6c757d',
        '学习中': '#17a2b8',
        '复习中': '#ffc107',
        '已掌握': '#28a745',
        '困难中': '#dc3545'
    }
    return color_map.get(status_name, '#6c757d')